#include "setting.h"
#include "ui_setting.h"
#include <QDebug>

Setting::Setting(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Setting)
{
    ui->setupUi(this);
    config = CabinetConfig::config();
    ui->server_address->setText(config->getApiAddress());
    ui->ctrl_address->setText(config->getCtrlAddress());
    ui->cabinet_id->setText(config->getCabinetId());
    ui->depart_id->setText(config->getDepartId());
    ui->depart_name->setText(config->getDepartName());
    ui->addr->setText(config->getIp());
    ui->gateway->setText(config->getGateway());
    initNameMap();
}

Setting::~Setting()
{
    delete ui;
}

void Setting::recvCardReader(QString cardId)
{
    qDebug()<<cardId;
    QString cardText = cardId;
//    int idx = cardIndex(cardText, listUser);
    ui->user_card->setText(cardText);
    updateUserTable();
}

int Setting::userIndex(QString id,QList<UserInfo *> users)
{
    int i = 0;
    foreach(UserInfo* info, users)
    {
        if(info->id == id)
        {
            config->setCurUser(info);
            return i;
        }
        i++;
    }
    return -1;
}

int Setting::cardIndex(QString card, QList<UserInfo *> users)
{
    int i = 0;
    foreach(UserInfo* info, users)
    {
        if(info->card == card)
            return i;
        i++;
    }
    return -1;
}

void Setting::selUser(int idx)
{
    if((idx < 0) || (idx > listUser.count()))
    {
        return;
    }
    UserInfo* user = listUser[idx];
    ui->user_name->setText(user->name);
    ui->user_id->setText(user->id);
    ui->user_card->setText(user->card);
    if(idx == 0)
    {
        if(ui->user_post->count() == 2)
            ui->user_post->addItem("管理员");
        ui->user_post->setEnabled(false);
        ui->user_name->setEnabled(true);
        ui->user_id->setEnabled(true);
        ui->user_card->setEnabled(true);
        ui->user_add->setEnabled(true);
        ui->user_del->setEnabled(false);
        ui->user_post->setEditText(user->post);
    }
    else
    {
        ui->user_post->setEnabled(true);
        ui->user_name->setEnabled(true);
        ui->user_id->setEnabled(true);
        ui->user_card->setEnabled(true);
        ui->user_add->setEnabled(true);
        ui->user_del->setEnabled(true);
        if(ui->user_post->count() == 3)
            ui->user_post->removeItem(2);
        if(user->post == "护士")
            ui->user_post->setCurrentIndex(0);
        else if(user->post == "护士长")
            ui->user_post->setCurrentIndex(1);
    }
}

void Setting::updateUserTable()
{
    int i=0;
    if(!listUser.isEmpty())
        qDeleteAll(listUser.begin(), listUser.end());

    listUser = config->getUsers();

    ui->users->clearContents();
    ui->users->setRowCount(listUser.count());
    ui->users->setColumnCount(4);

    QStringList posts;
    posts<<"管理员"<<"护士"<<"护士长";
    ui->user_post->clear();
    ui->user_post->addItems(posts);

    foreach(UserInfo* info, listUser)
    {
        ui->users->setItem(i,0,new QTableWidgetItem(info->name));
        ui->users->setItem(i,1,new QTableWidgetItem(info->post));
        ui->users->setItem(i,2,new QTableWidgetItem(info->id));
        ui->users->setItem(i,3,new QTableWidgetItem(info->card));
        i++;
    }
}

UserInfo* Setting::checkInfo()
{
    QString name = ui->user_name->text();
    QString card = ui->user_card->text().toLower();
    QString post = ui->user_post->currentText();
    QString id = ui->user_id->text();
    if(name.isEmpty() || card.isEmpty() || post.isEmpty() || id.isEmpty())
        return NULL;
//    if(userIndex(id, listUser) != -1)
//        return NULL;

    return new UserInfo(name, post, id, card);
}

void Setting::initNameMap()
{
    if(!nameMap.isEmpty())
        return;
    nameMap.insert("2CF", QString::fromUtf8("临检室1号"));
    nameMap.insert("26D", QString::fromUtf8("临检室2号"));
    nameMap.insert("0D5", QString::fromUtf8("微生物室1号"));
    nameMap.insert("E0B", QString::fromUtf8("微生物室2号"));
    nameMap.insert("B29", QString::fromUtf8("生化室"));
    nameMap.insert("D4F", QString::fromUtf8("艾滋病初筛"));
    nameMap.insert("F14", QString::fromUtf8("发光室1号"));
    nameMap.insert("DE5", QString::fromUtf8("发光室(海尔)2号"));
    nameMap.insert("C44", QString::fromUtf8("血库1号"));
    nameMap.insert("E75", QString::fromUtf8("血库(海尔)2号"));
    nameMap.insert("C64", QString::fromUtf8("SPD仓(大)1号"));
    nameMap.insert("921", QString::fromUtf8("SPD仓(小)2号"));

    QString strTab = QString();
    strTab += printMapTab("2CF", QString::fromUtf8("临检室1号"));
    strTab += printMapTab("26D", QString::fromUtf8("临检室2号"));
    strTab += printMapTab("0D5", QString::fromUtf8("微生物室1号"));
    strTab += printMapTab("E0B", QString::fromUtf8("微生物室2号"));
    strTab += printMapTab("B29", QString::fromUtf8("生化室"));
    strTab += printMapTab("D4F", QString::fromUtf8("艾滋病初筛"));
    strTab += printMapTab("F14", QString::fromUtf8("发光室1号"));
    strTab += printMapTab("DE5", QString::fromUtf8("发光室(海尔)2号"));
    strTab += printMapTab("C44", QString::fromUtf8("血库1号"));
    strTab += printMapTab("E75", QString::fromUtf8("血库(海尔)2号"));
    strTab += printMapTab("C64", QString::fromUtf8("SPD仓(大)1号"));
    strTab += printMapTab("921", QString::fromUtf8("SPD仓(小)2号"));
//    qDebug()<<strTab;
//    ui->textLab->setText(strTab);
}

QString Setting::printMapTab(QString key, QString val)
{
    bool ok;
//    qDebug()<<key.toInt(&ok, 16)<<val;
    return QString::number(key.toInt(&ok, 16), 10)+" "+val+"\n";
}

void Setting::on_user_add_clicked()
{
    UserInfo* info = checkInfo();
    if(info == NULL)
    {
        QMessageBox::information(this, "添加用户", "添加用户失败:用户信息不完整", QMessageBox::Ok);
        return;
    }
    int idx = userIndex(info->id, listUser);
    if(idx == -1)
    {
        if(cardIndex(info->card, listUser) != -1)
        {
            QMessageBox::information(this, "添加用户", "添加用户失败:卡号重复", QMessageBox::Ok);
            return;
        }
        if(!listUser.isEmpty())
        {
            if((info->post == "管理员") && (info->id != listUser.at(0)->id))
            {
                QMessageBox::information(this, "添加用户", "添加用户失败:不允许修改管理员ID", QMessageBox::Ok);
                return;
            }
        }
        listUser<<info;
        config->addUser(info);
        updateUserTable();
    }
    else
    {
        if(idx == 0 && info->post != "管理员")
        {
            QMessageBox::information(this, "添加用户", "添加用户失败:将管理员变更为非管理员", QMessageBox::Ok);
            return;
        }
        if((cardIndex(info->card, listUser) != -1) && (cardIndex(info->card, listUser) != idx))
        {
            QMessageBox::information(this, "添加用户", "添加用户失败:卡号重复", QMessageBox::Ok);
            return;
        }
        if((info->post == "管理员") && (info->id != listUser.at(0)->id))
        {
            QMessageBox::information(this, "添加用户", "添加用户失败:不允许修改管理员id", QMessageBox::Ok);
            return;
        }
        listUser.removeAt(idx);
        listUser.insert(idx, info);
        config->addUser(info);
        updateUserTable();
    }
    QMessageBox::information(this, "添加用户", "添加用户成功", QMessageBox::Ok);
}

void Setting::on_user_del_clicked()
{
    UserInfo* info = checkInfo();
    if(info == NULL)
    {
        QMessageBox::information(this, "删除用户", "删除用户失败", QMessageBox::Ok);
        return;
    }
    int index = userIndex(info->id, listUser);
    if(index == -1)
    {
        QMessageBox::information(this, "删除用户", "删除用户失败：用户不存在", QMessageBox::Ok);
        return;
    }
    info = listUser.at(index);
    listUser.removeAt(index);
    config->removeUser(info);
    updateUserTable();
    QMessageBox::information(this, "删除用户", "删除用户成功", QMessageBox::Ok);
}

void Setting::on_users_cellClicked(int row, int)
{
//    emit selUserChanged(row);
    selUser(row);
}

void Setting::on_user_clear_clicked()
{
    ui->user_post->setEnabled(true);
    ui->user_name->setEnabled(true);
    ui->user_id->setEnabled(true);
    ui->user_card->setEnabled(true);
    ui->user_add->setEnabled(true);
    ui->user_del->setEnabled(true);

    ui->user_post->clear();
    ui->user_name->clear();
    ui->user_card->clear();
    ui->user_id->clear();

    QStringList posts;
    posts<<"护士"<<"护士长";
    ui->user_post->clear();
    ui->user_post->addItems(posts);
}

//void Setting::on_cabinet_id_editingFinished()
//{
//    QString cabId = ui->cabinet_id->text();
//    config->setCabinetId(cabId);
//    emit updateCabinetId(cabId);
//}

//void Setting::on_depart_name_editingFinished()
//{
//    QString departName = ui->depart_name->text();
//    config->setDepartName(departName);
//    emit updateDepartName(departName);
//    ui->departName->setText(departName);
//}

void Setting::on_server_address_editingFinished()
{
    config->setApiAddress(ui->server_address->text());
    emit updateServerAddr(ui->server_address->text());
}

void Setting::on_ctrl_address_editingFinished()
{
    config->setCtrlAddress(ui->ctrl_address->text());
    emit updateCtrlAddr(ui->ctrl_address->text());
}

void Setting::on_depart_id_editingFinished()
{
    QString departStr = ui->depart_id->text();
//    if(nameMap.contains(departStr))
//        return;
//    bool ok;
//    int departNum = departStr.toInt(&ok, 10);
//    departStr = QString::number(departNum, 16).toUpper();
//    while(departStr.length() < 3)
//        departStr.insert(0, '0');
//    ui->depart_id->setText(departStr);

    QString departName = departStr;
    ui->depart_name->setText(departName);

    QString cabinetId = departStr;
    ui->cabinet_id->setText(cabinetId);

    config->setDepartId(ui->depart_id->text());
    config->setDepartName(ui->depart_name->text());
    config->setCabinetId(ui->cabinet_id->text());
    emit updateCabinetInfo(ui->depart_id->text(), ui->depart_name->text());
}

void Setting::on_back_clicked()
{
    emit reqCloseSetting();
}

void Setting::on_ok_clicked()
{
    config->setDevice();
    config->setIp(ui->addr->text());
    config->setGateway(ui->gateway->text());
}

//void Setting::on_setTime_clicked()
//{
//    QProcess p;
//    QString cmd = QString("date -s \"%1\"").arg(QDateTime::fromString(ui->strTime->text(), "yyyyMMddhhmm").toString("yyyy-MM-dd hh:mm:ss"));
//    qDebug()<<"set time"<<cmd;
//    p.start(cmd);
//    p.waitForFinished();
//}

void Setting::on_setTime_clicked()
{
    QString tStr = QDateTime::fromString(ui->strTime->text(), "yyyyMMddhhmm").toString("yyyy-MM-dd hh:mm:ss");
    QString cmd = QString("date -s \"%1\"").arg(tStr);
    QProcess p;
    p.start(cmd);
    p.waitForFinished();
}
